package com.redis.demo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author zqf
 * @Date 2022/10/27 16:13
 * @Description: list类型
 */
@RestController("/listKey")
@Api(tags = "redis对集合list的操作")
public class ListRedisController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("addList")
    @ApiOperation("添加元素到List并返回")
    public List<Object> testHsetHash(@RequestParam("redisKey") String redisKey, @RequestParam("size") Integer size) {
        //双向链表
        for (Integer i = 0; i < size; i++) {
            //往链表的左边添加一个元素
            redisTemplate.opsForList().leftPush(redisKey,i);
            //往链表的右边添加一个元素
            //redisTemplate.opsForList().rightPush()
        }
        return redisTemplate.opsForList().range(redisKey,0,-1);
    }


    @GetMapping("leftPushAll")
    @ApiOperation("往头部添加多个元素")
    public List<Object> leftPushAll (@RequestParam("redisKey") String redisKey) {
        redisTemplate.opsForList().leftPushAll(redisKey,"22","33","44");
       // redisTemplate.opsForList().rightPushAll(redisKey,"22","33","44");
        return redisTemplate.opsForList().range(redisKey,0,-1);
    }

    @GetMapping("set")
    @ApiOperation("设置改key的list集合下标为0的值，必须存在key")
    public Boolean set(@RequestParam("redisKey") String redisKey,@RequestParam("value")String value) {
        redisTemplate.opsForList().set(redisKey,0,value);
     return true;
    }


    @GetMapping("index")
    @ApiOperation("获取指定下标的值")
    public Object index (@RequestParam("redisKey") String redisKey) {
        return redisTemplate.opsForList().index(redisKey, 0);
    }


    @GetMapping("leftPop")
    @ApiOperation("返回和移除列表的第一个元素")
    public List<Object> leftPop (@RequestParam("redisKey") String redisKey) {
        //第一个
        Object o = redisTemplate.opsForList().leftPop(redisKey);
        //最后一个
        Object o1 = redisTemplate.opsForList().rightPop(redisKey);
        return redisTemplate.opsForList().range(redisKey,0,-1);
    }


    @GetMapping("size")
    @ApiOperation("返回集合的长度")
    public Object size (@RequestParam("redisKey") String redisKey) {
        return redisTemplate.opsForList().size(redisKey);
    }

}
